#include "VerifyGrpcClient.h"

GRPCConPool::GRPCConPool(size_t pool_size, std::string host, std::string port)
	: m_pool_size(pool_size), m_host(host)
	, m_port(port), m_b_stop(false)
{
	for (size_t i = 0; i < m_pool_size; ++i) {
		std::shared_ptr<grpc::Channel> channel = grpc::CreateChannel(host + ":" + port, grpc::InsecureChannelCredentials());
		m_connections.push(message::VerifyService::NewStub(channel));
	}
}

GRPCConPool::~GRPCConPool()
{
	std::lock_guard<std::mutex> lock(m_mutex);
	Close();
	while (!m_connections.empty()) {
		m_connections.pop();
	}
}

std::unique_ptr<message::VerifyService::Stub> GRPCConPool::getConnection()
{
	std::unique_lock<std::mutex> lock(m_mutex);
	m_cond.wait(lock, [this]() {
		if (m_b_stop) {
			return true;
		}

		return !m_connections.empty();
	});

	if (m_b_stop) {
		return nullptr;
	}

	auto stub = std::move(m_connections.front());
	m_connections.pop();

	return stub;
}

void GRPCConPool::returnConnection(std::unique_ptr<message::VerifyService::Stub> stub)
{
	std::lock_guard<std::mutex> lock(m_mutex);
	if (m_b_stop) {
		return;
	}

	m_connections.push(std::move(stub));
	m_cond.notify_one();
}

void GRPCConPool::Close()
{
	m_b_stop = true;
	m_cond.notify_all();
}

